﻿/*************************************************
作者: Plane
邮箱: 1785275942@qq.com
功能: 关卡加载系统

           ~~获取更多教学资讯~~
//----------------*----------------\\
        教学官网：www.qiqiker.com
        官方微信服务号: qiqikertuts
        Plane老师微信: PlaneZhong
\\----------------*----------------//
*************************************************/

using System;
using PEProtocol;
using UnityEngine;

public class StageSys : ILogic {
    //-------------Declaration----------------//
    PERoot root; ResSvc resSvc; UISvc uiSvc;
    Action loadStageDone;
    int currentStageID;
    public int CurrentStageID { get => currentStageID; }
    StageCfg cfg;

    //-------------Flow Functions-------------//
    public void Init() {
        root = PERoot.Instance;
        resSvc = root.resSvc;
        uiSvc = root.uiSvc;
        this.Log("Init AcctSys Done.");
    }
    public void Tick() {
        //Note:模拟跳转关卡通知下达
        if (Input.GetKeyDown(KeyCode.Alpha2)) {
            NtfEnterStage(new NetMsg {
                cmd = CMD.NtfEnterStage,
                ntfEnterStage = new() {
                    stageID = 2
                }
            });
        }
        if (Input.GetKeyDown(KeyCode.Alpha3)) {
            NtfEnterStage(new NetMsg {
                cmd = CMD.NtfEnterStage,
                ntfEnterStage = new() {
                    stageID = 101
                }
            });
        }
    }
    public void UnInit() {
        this.Log("UnInit AcctSys.");
    }

    //-------------Core Functions-------------//
    public void NtfEnterStage(NetMsg msg) {
        NtfEnterStage ntf = msg.ntfEnterStage;
        LoadGameStage(ntf.stageID, () => {
            root.EnterGameMode(XlsCfgTool.GetStageConfig(ntf.stageID).playMode);
        });
    }
    public void LoadGameStage(int stageID, Action loadStageDone) {
        currentStageID = stageID;
        this.loadStageDone = loadStageDone;
        cfg = XlsCfgTool.GetStageConfig(stageID);

        if (cfg.isGhost) {
            //镜像场景地图：水波屏幕特效过渡 #TODO
            this.LogGreen("TODO 水波屏幕特效过渡");
        }
        else {
            uiSvc.SetLoading(0, true);
        }

        LoadScene(cfg.sceneName);
    }

    //-------------Tool Functions-------------//
    void LoadScene(string sceneName) {
        resSvc.LoadSceneAsync(sceneName,
            (progress) => {
                UpdateLoaingProgress(progress);
            },
            () => {
                UpdateLoaingProgress(1);
            });
    }
    void UpdateLoaingProgress(float progress) {
        this.LogCyan($"load:{progress}");
        int loadPercentage = (int)(progress * 100);

        if (loadStageDone != null && !cfg.isGhost) {
            uiSvc.SetLoading(loadPercentage);
        }
        if (loadPercentage == 100) {
            loadStageDone?.Invoke();
            loadStageDone = null;
        }
    }
}